package com.winapi.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.winapi.project.annotation.AuthCheck;
import com.winapi.project.common.BaseResponse;
import com.winapi.project.common.DeleteRequest;
import com.winapi.project.common.ErrorCode;
import com.winapi.project.common.ResultUtils;
import com.winapi.project.constant.CommonConstant;
import com.winapi.project.constant.UserConstant;
import com.winapi.project.exception.BusinessException;
import com.winapi.project.model.dto.interfaceinfo.*;
import com.winapi.project.model.enums.InterfaceInfoStatusEnum;
import com.winapi.project.model.vo.InterfaceInfoVO;
import com.winapi.project.service.InterfaceInfoService;
import com.winapi.project.service.UserInterfaceInfoService;
import com.winapi.project.service.UserService;
import com.winapi.winapiclientsdk.client.WinapiClient;
import com.winapi.winapicommon.model.entity.InterfaceInfo;
import com.winapi.winapicommon.model.entity.User;
import com.winapi.winapicommon.model.entity.UserInterfaceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 帖子接口
 *
 * @author 张莹莹
 * @from
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j

public class InterfaceInfoController {
    private static final String interfaceInfoLog="接口模块-";
    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private UserService userService;
    @Resource
    private WinapiClient winapiClient;
    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addinterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        log.info(interfaceInfoLog+"新增接口-正在调用接口....");
        if (interfaceInfoAddRequest == null) {
            log.error(interfaceInfoLog+"新增接口-参数为空");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest, interfaceInfo);
        interfaceInfoService.validInterfaceInfo(interfaceInfo, true);
        log.info(interfaceInfoLog+"新增接口-参数都符合规则");
        User loginUser = userService.getLoginUser(request);
        log.info(interfaceInfoLog+"新增接口-获取当前登录态信息");
        interfaceInfo.setUserId(loginUser.getId());
        boolean result = interfaceInfoService.save(interfaceInfo);
        log.info(interfaceInfoLog+"新增接口-将新创建的接口插入接口表");
        if (!result) {
            log.error(interfaceInfoLog+"新增接口-插入数据失败");
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        long newinterfaceInfoId = interfaceInfo.getId();
        log.info(interfaceInfoLog+"新增接口-结束调用接口....");
        return ResultUtils.success(newinterfaceInfoId);

    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteinterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        log.info(interfaceInfoLog+"删除接口-正在调用接口....");
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            log.error(interfaceInfoLog+"删除接口-请求参数为空/接口id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        log.info(interfaceInfoLog+"删除接口-获取当前登录态");
        long id = deleteRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        log.info(interfaceInfoLog+"删除接口-根据接口id获取当前接口信息");
        if (oldInterfaceInfo == null) {
            log.info(interfaceInfoLog+"删除接口-接口不存在");
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            log.info(interfaceInfoLog+"删除接口-没有删除权限");
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = interfaceInfoService.removeById(id);
        log.info(interfaceInfoLog+"删除接口-根据接口id在数据库中删除这个记录");
        log.info(interfaceInfoLog+"删除接口-结束调用接口....");
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param interfaceInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateinterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest
    ,HttpServletRequest request) {
        log.info(interfaceInfoLog+"修改接口-正在调用接口....");
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            log.info(interfaceInfoLog+"修改接口-参数为空/接口id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest, interfaceInfo);

        // 参数校验
        interfaceInfoService.validInterfaceInfo(interfaceInfo, false);
        log.info(interfaceInfoLog+"修改接口-参数校验，都合法");
        User user = userService.getLoginUser(request);
        log.info(interfaceInfoLog+"修改接口-获取当前登录态信息");
        long id = interfaceInfoUpdateRequest.getId();
        // 判断是否存在
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        log.info(interfaceInfoLog+"修改接口-根据接口id获取接口信息");
        if(oldInterfaceInfo==null){
            log.info(interfaceInfoLog+"上线接口-接口不存在");
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可修改
        if (!oldInterfaceInfo.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            log.info(interfaceInfoLog+"修改接口-没有权限修改");
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        log.info(interfaceInfoLog+"修改接口-在数据库中修改接口信息");
        log.info(interfaceInfoLog+"修改接口-结束调用接口....");
        return ResultUtils.success(result);
    }

    /**
     * 上线
     *
     * @param idInterfaceInfoRequest
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> onlineinterfaceInfo(@RequestBody IdInterfaceInfoRequest idInterfaceInfoRequest
            ,HttpServletRequest request) {
        log.info(interfaceInfoLog+"上线接口-正在调用接口....");
        //1.判断接口的id是否为空或错误
        if (idInterfaceInfoRequest == null || idInterfaceInfoRequest.getId() <= 0) {
            log.info(interfaceInfoLog+"上线接口-参数为空/接口id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //1.校验接口是否存在
        Long id = idInterfaceInfoRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        log.info(interfaceInfoLog+"上线接口-根据接口id获取接口信息");
        if(oldInterfaceInfo==null){
            log.error(interfaceInfoLog+"上线接口-接口不存在");
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //2.接口验证，是否可以调用
        com.winapi.winapiclientsdk.model.User user = new com.winapi.winapiclientsdk.model.User();
        user.setUsername("test");
        String userNameByPost = winapiClient.getUserNameByPost(user);
        log.info(interfaceInfoLog+"上线接口-调用接口");
        if(StringUtils.isBlank(userNameByPost)){
            log.error(interfaceInfoLog+"上线接口-接口调用失败");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"接口验证");
        }
        //3.修改接口数据库中的状态字段为上线
        final InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(idInterfaceInfoRequest.getId());
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.ONLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        log.info(interfaceInfoLog+"上线接口-更新接口状态为在线");
        log.info(interfaceInfoLog+"上线接口-结束调用接口....");
        return ResultUtils.success(result);
    }


    /**
     * 下线（仅管理员）
     *
     * @param idInterfaceInfoRequest
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> offlineinterfaceInfo(@RequestBody IdInterfaceInfoRequest idInterfaceInfoRequest
            ,HttpServletRequest request) {
        log.info(interfaceInfoLog+"下线接口-正在调用接口....");
      //1.判断接口的id是否为空或错误
        if (idInterfaceInfoRequest == null || idInterfaceInfoRequest.getId() <= 0) {
            log.info(interfaceInfoLog+"上线接口-参数为空/接口id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //1.校验接口是否存在
        Long id = idInterfaceInfoRequest.getId();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        log.info(interfaceInfoLog+"上线接口-根据接口id获取接口信息");
        if(oldInterfaceInfo==null){
            log.info(interfaceInfoLog+"上线接口-接口不存在");
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //2.修改接口数据库中的状态字段为上线
        final InterfaceInfo interfaceInfo = new InterfaceInfo();
        interfaceInfo.setId(idInterfaceInfoRequest.getId());
        interfaceInfo.setStatus(InterfaceInfoStatusEnum.OFFLINE.getValue());
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        log.info(interfaceInfoLog+"下线接口-更新接口状态为离线");
        log.info(interfaceInfoLog+"下线接口-结束调用接口....");
        return ResultUtils.success(result);
    }


    /**
     * 测试调用（仅管理员）
     *
     * @param interfaceInfoInvokeRequest
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody InterfaceInfoInvokeRequest interfaceInfoInvokeRequest
            ,HttpServletRequest request) {
        log.info(interfaceInfoLog+"调用接口-正在调用接口....");
        //1.判断接口的id是否为空或错误
        if (interfaceInfoInvokeRequest == null || interfaceInfoInvokeRequest.getId() <= 0) {
            log.info(interfaceInfoLog+"调用接口-参数不为空/接口id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //1.校验接口是否存在
        Long id = interfaceInfoInvokeRequest.getId();
        String userRequestParams = interfaceInfoInvokeRequest.getUserRequestParams();
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(id);
        log.info(interfaceInfoLog+"调用接口-根据接口id查询接口信息");
        if(oldInterfaceInfo==null){
            log.info(interfaceInfoLog+"调用接口-接口不存在");
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if(oldInterfaceInfo.getStatus()==InterfaceInfoStatusEnum.OFFLINE.getValue()){
            log.info(interfaceInfoLog+"调用接口-接口不在线");
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"接口已关闭");
        }
        User loginUser = userService.getLoginUser(request);
        log.info(interfaceInfoLog+"调用接口-获取当前登录态");
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        //用户调用次数校验
        QueryWrapper<UserInterfaceInfo> userInterfaceInfoQueryWrapper = new QueryWrapper<>();
        userInterfaceInfoQueryWrapper.eq("userId", loginUser.getId());
        userInterfaceInfoQueryWrapper.eq("interfaceInfoId", id);
        UserInterfaceInfo userInterfaceInfo = userInterfaceInfoService.getOne(userInterfaceInfoQueryWrapper);
        log.info(interfaceInfoLog+"调用接口-根据接口id和用户id在用户接口表中查询这条记录");
        if (userInterfaceInfo == null){
            log.error(interfaceInfoLog+"调用接口-用户接口记录不存在");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户接口记录不存在");
        }
        int leftNum = userInterfaceInfo.getLeftNum();
        if(leftNum <= 0){
            log.error(interfaceInfoLog+"调用接口-调用次数不足");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "调用次数不足！");
        }
        //发起接口调用
        String sdk = oldInterfaceInfo.getSdk();
        String name = oldInterfaceInfo.getName();
        log.info(interfaceInfoLog+"调用接口-正在反射调用自己写的接口.....");
        Object res= invokeSdk(sdk,name,userRequestParams,accessKey,secretKey);
        log.info(interfaceInfoLog+"调用接口-反射调用自己写的接口结束.....");
        if (res == null) {
            log.info(interfaceInfoLog+"调用接口-调用结果不存在");
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (res.toString().contains("Error request")) {
            log.info(interfaceInfoLog+"调用接口-调用错误，请检查参数和接口调用次数！");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "调用错误，请检查参数和接口调用次数！");
        }
//         WinapiClient tempapiClient = new WinapiClient(accessKey, secretKey);
//        Gson gson = new Gson();
//        com.winapi.winapiclientsdk.model.User user = gson.fromJson(userRequestParams, com.winapi.winapiclientsdk.model.User.class);
//        String userNameByPost = tempapiClient.getUserNameByPost(user);
        log.info(interfaceInfoLog+"调用接口-结束调用接口....");
        return ResultUtils.success(res);
    }


    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfoVO> getinterfaceInfoVOById(long id, HttpServletRequest request) {
        log.info(interfaceInfoLog+"根据接口id获取接口信息-正在调用接口.....");
        if (id <= 0) {
            log.info(interfaceInfoLog+"根据接口id获取接口信息-接口id不合法");
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        log.info(interfaceInfoLog+"根据接口id获取接口信息-根据接口id在数据库中查询接口信息");
        BeanUtils.copyProperties(interfaceInfo,interfaceInfoVO);
         //获取登录态
        User loginUser = userService.getLoginUser(request);
        log.info(interfaceInfoLog+"根据接口id获取接口信息-获取当前登录态");
        Long userId = loginUser.getId();
        try{
            //根据interfaceIfoId和userId来获取关系表信息
            UserInterfaceInfo userInterfaceInfo=userInterfaceInfoService.getInterfaceInfoByUserIdAndInterfaceInfoId(userId,id);
            log.info(interfaceInfoLog+"根据接口id获取接口信息-根据interfaceIfoId和userId来获取关系表信息");
            interfaceInfoVO.setLeftNum(userInterfaceInfo.getLeftNum());
        }catch (NullPointerException e){
            log.info(interfaceInfoLog+"根据接口id获取接口信息-捕获NullPointerException");
            interfaceInfoVO.setLeftNum(0);
        }
        log.info(interfaceInfoLog+"根据接口id获取接口信息-结束调用接口.....");
        return ResultUtils.success(interfaceInfoVO);

    }

    /**
     * 分页获取列表（封装类）
     * @param interfaceInfoQueryRequest
     * @return
     */
    @AuthCheck(mustRole = "admin")
    @GetMapping("/list")
    public BaseResponse<List<InterfaceInfo>> listInterfaceInfo(InterfaceInfoQueryRequest interfaceInfoQueryRequest) {
        log.info(interfaceInfoLog+"分表获取接口列表-正在调用接口.....");
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        if (interfaceInfoQueryRequest != null) {
            BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(queryWrapper);
        log.info(interfaceInfoLog+"分表获取接口列表-结束调用接口.....");
        return ResultUtils.success(interfaceInfoList);
    }


    /**
     * 分页获取列表
     *
     * @param interfaceInfoQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<InterfaceInfo>> listInterfaceInfoByPage(InterfaceInfoQueryRequest interfaceInfoQueryRequest, HttpServletRequest request) {
        if (interfaceInfoQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        InterfaceInfo interfaceInfoQuery = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoQueryRequest, interfaceInfoQuery);
        long current = interfaceInfoQueryRequest.getCurrent();
        long size = interfaceInfoQueryRequest.getPageSize();
        String sortField = interfaceInfoQueryRequest.getSortField();
        String sortOrder = interfaceInfoQueryRequest.getSortOrder();
        String description = interfaceInfoQuery.getDescription();
        // description 需支持模糊搜索
        interfaceInfoQuery.setDescription(null);
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<InterfaceInfo> queryWrapper = new QueryWrapper<>(interfaceInfoQuery);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(interfaceInfoPage);
    }
    @GetMapping("/sdk")
    public void getSdk(HttpServletRequest request, HttpServletResponse response)throws IOException{
        //1.登录态是否存在
        User loginUser = userService.getLoginUser(request);
        if(loginUser==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"登录态不存在");
        }
            // 获取要下载的文件,add resources,please open this project again
InputStream in =  Thread.currentThread().getContextClassLoader().getResourceAsStream("winapi-client-sdk-0.0.1.jar");
        // 获取要下载的文件
//        org.springframework.core.io.Resource resource = new ClassPathResource("winapi-client-sdk-0.0.1.jar");
//        InputStream in = resource.getInputStream();
        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=api-client-sdk-0.0.1.jar");

        // 将文件内容写入响应
        try (OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            out.flush();

        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        }finally {
            in.close();
        }
    }
    // endregion
private Object invokeSdk(String classPath,String name,String requestParams,String accessKey,String secretKey){
    try {
        //通过类路径获取对应的类
        Class<?> aClass = Class.forName(classPath);
        //通过构造体获取对应类对象
        Constructor<?> winClientConstructor = aClass.getConstructor(String.class,String.class);
        //通过构造器构造出对应的客户端
        Object winClient = winClientConstructor.newInstance(accessKey,secretKey);
        //客户端调用对应的接口，实现接口调用
        Method[] methods = aClass.getMethods();
        for(Method method:methods){
            if(method.getName().equals(name)){
                // 3.1 获取参数类型列表
                Class<?>[] parameterTypes = method.getParameterTypes();
                //如果接口无参数，直接调用
                if(parameterTypes.length==0){
                    return method.invoke(winClient);
                }
                   Gson gson = new Gson();
                // 构造参数
                 Object parameter = gson.fromJson(requestParams, parameterTypes[0]);
                 Object invoke = method.invoke(winClient, parameter);
                return invoke;
            }
        }
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        throw new BusinessException(ErrorCode.SYSTEM_ERROR, "找不到调用的方法!! 请检查你的请求参数是否正确!");
    }

}

}
